#include <iostream>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>
#include <cstring>

void *my_malloc(size_t size)
{
    if (size > 0)
    {
        void *ptr = ::mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        if (ptr == MAP_FAILED)
        {
            return nullptr;
        }
        return ptr;
    }
    return nullptr;
}

void my_free(void *ptr, size_t size)
{
    if (ptr != nullptr && size != 0)
    {
        int ret = munmap(ptr, size);
        if(ret != 0)
        {
            std::cerr << "munmap failed" << std::endl;
        }
    }
}

int main()
{
    char* ptr = (char*)my_malloc(1024);
    if(ptr == nullptr)
    {
        std::cerr << "my_malloc failed" << std::endl;
        return 1;
    }

    // 使用分配的内存 (这里只是简单地打印指针值)
    printf("Allocated memory at address: %p\n", ptr);

    //...在这里可以使用ptr指向的内存...
    memset(ptr, 'A', 1024);

    for (int i = 0; i < 1024; i++)
    {
        printf("%c ", ptr[i]);
        fflush(stdout);
        sleep(1);
    }

    my_free(ptr, 1024);

    return 0;
}